package com.jake.rabbit.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;
import java.util.Map;

@Slf4j
public class HttpClientUtils {

    private static CloseableHttpClient httpClient = HttpClients.createMinimal();

    public static Map<String, Object> getResponseMap(@RequestBody Map<String, Object> requestMap, String url) {
        HttpPost httpPost = new HttpPost(url);
        String requestJson = JSON.toJSONString(requestMap);
        StringEntity stringEntity = new StringEntity(requestJson, "UTF-8");
        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);
        try {
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                String responseJson = EntityUtils.toString(httpResponse.getEntity());
                return JSON.parseObject(responseJson);
            } else {
                log.error("the httpResponse is {}", httpResponse);
            }
        } catch (IOException e) {
            log.error("Fail to execute httpClient.", e);
        } finally {
            httpPost.releaseConnection();
        }
        log.error("httpclient 出现故障");
        return null;
    }

}
